package com.steven.sync;

import java.util.concurrent.Semaphore;

/**
 * 信号量:允许多个线程,
 * 举例：最多允许多少个线程同时来运行， 收费站
 * 有公平和不公平两种情况：就是进收费站的时候 有车可以插队，公平就是排队
 * 限流
 */
public class Semaphore_test {

    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(2);
        new Thread(()->{
            try {
                //获取许可
                semaphore.acquire();
                System.out.println("t1 run");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        }).start();

        new Thread(()->{
            try {
                semaphore.acquire();
                System.out.println("t2 run");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        }).start();

    }


}
